from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse
from fastapi.openapi.docs import get_swagger_ui_html, get_redoc_html
# 临时只导入文档管理相关模块，避免依赖问题
from app.routes import documents, zip_manager
# from app.routes import user, calendar, weather, bus_station, wechat_management
# from app.routes import bus_station, user, wechat_management, calendar, weather

# 创建FastAPI应用实例
app = FastAPI(
    title="WebAPI - 文档管理系统",
    description="基于 FastAPI 开发的文档管理系统，支持ZIP文件处理和Markdown文档管理",
    version="1.0.0",
    docs_url=None,  # 禁用默认docs
    redoc_url=None  # 禁用默认redoc
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/docs", response_class=HTMLResponse)
async def custom_api_docs():
    """自定义API文档页面"""
    html_content = """
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>📚 文档管理系统 API</title>
        <style>
            /* Bootstrap 核心样式 - 内联版本 */
            * { box-sizing: border-box; }
            body { 
                margin: 0; 
                font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;
                font-size: 1rem; 
                font-weight: 400; 
                line-height: 1.5; 
                color: #212529; 
                background-color: #f8f9fa; 
            }
            .container { 
                width: 100%; 
                padding-right: 15px; 
                padding-left: 15px; 
                margin-right: auto; 
                margin-left: auto; 
                max-width: 1140px;
            }
            .py-5 { padding-top: 3rem!important; padding-bottom: 3rem!important; }
            .mb-5 { margin-bottom: 3rem!important; }
            .mt-5 { margin-top: 3rem!important; }
            .text-center { text-align: center!important; }
            .text-muted { color: #6c757d!important; }
            .lead { font-size: 1.25rem; font-weight: 300; }
            .row { display: flex; flex-wrap: wrap; margin-right: -15px; margin-left: -15px; }
            .col-md-8 { flex: 0 0 66.666667%; max-width: 66.666667%; }
            .mx-auto { margin-right: auto!important; margin-left: auto!important; }
            .card { 
                position: relative; 
                display: flex; 
                flex-direction: column; 
                min-width: 0; 
                word-wrap: break-word; 
                background-color: #fff; 
                background-clip: border-box; 
                border: 1px solid rgba(0,0,0,.125); 
                border-radius: 0.25rem; 
                margin-bottom: 20px;
            }
            .card-header { 
                padding: 0.75rem 1.25rem; 
                margin-bottom: 0; 
                background-color: rgba(0,0,0,.03); 
                border-bottom: 1px solid rgba(0,0,0,.125);
                border-top-left-radius: calc(0.25rem - 1px);
                border-top-right-radius: calc(0.25rem - 1px);
            }
            .card-body { flex: 1 1 auto; padding: 1.25rem; }
            .badge { 
                display: inline-block; 
                padding: 0.25em 0.4em; 
                font-size: 75%; 
                font-weight: 700; 
                line-height: 1; 
                text-align: center; 
                white-space: nowrap; 
                vertical-align: baseline; 
                border-radius: 0.25rem;
            }
            .bg-primary { background-color: #007bff!important; color: white; }
            .bg-success { background-color: #28a745!important; color: white; }
            .bg-info { background-color: #17a2b8!important; color: white; }
            .alert { 
                position: relative; 
                padding: 0.75rem 1.25rem; 
                margin-bottom: 1rem; 
                border: 1px solid transparent; 
                border-radius: 0.25rem;
            }
            .alert-info { 
                color: #0c5460; 
                background-color: #d1ecf1; 
                border-color: #bee5eb;
            }
            .bg-light { background-color: #f8f9fa!important; }
            .p-2 { padding: 0.5rem!important; }
            .rounded { border-radius: 0.25rem!important; }
            code { 
                font-size: 87.5%; 
                color: #e83e8c; 
                word-wrap: break-word;
                font-family: SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;
            }
            h1 { font-size: 2.5rem; }
            h5 { font-size: 1.25rem; }
            .method-get { background-color: #d1ecf1; border-color: #bee5eb; }
            .method-post { background-color: #d4edda; border-color: #c3e6cb; }
            .method-put { background-color: #fff3cd; border-color: #ffeaa7; }
            .method-delete { background-color: #f8d7da; border-color: #f5c6cb; }
            a { color: #007bff; text-decoration: none; }
            a:hover { color: #0056b3; text-decoration: underline; }
            @media (max-width: 768px) {
                .col-md-8 { flex: 0 0 100%; max-width: 100%; }
                .container { padding-right: 10px; padding-left: 10px; }
            }
        </style>
    </head>
    <body>
        <div class="container py-5">
            <div class="text-center mb-5">
                <h1>📚 文档管理系统 API</h1>
                <p class="lead">ZIP文件处理和Markdown文档管理接口</p>
                <div class="alert alert-info">
                    <strong>基础地址:</strong> http://localhost:8080
                </div>
            </div>

            <div class="row">
                <div class="col-md-8 mx-auto">
                    <!-- 获取文档列表 -->
                    <div class="card api-card method-get">
                        <div class="card-header">
                            <h5><span class="badge bg-primary">GET</span> /api/documents</h5>
                        </div>
                        <div class="card-body">
                            <p><strong>功能:</strong> 获取所有文档列表</p>
                            <p><strong>响应:</strong> 返回ZIP文件解压后的文档项目列表</p>
                            <div class="bg-light p-2 rounded">
                                <code>curl -X GET "http://localhost:8080/api/documents"</code>
                            </div>
                        </div>
                    </div>

                    <!-- 获取文档详情 -->
                    <div class="card api-card method-get">
                        <div class="card-header">
                            <h5><span class="badge bg-primary">GET</span> /api/documents/{doc_id}</h5>
                        </div>
                        <div class="card-body">
                            <p><strong>功能:</strong> 获取指定文档的详细信息</p>
                            <p><strong>参数:</strong> doc_id - 文档ID</p>
                            <div class="bg-light p-2 rounded">
                                <code>curl -X GET "http://localhost:8080/api/documents/1"</code>
                            </div>
                        </div>
                    </div>

                    <!-- 获取文件内容 -->
                    <div class="card api-card method-get">
                        <div class="card-header">
                            <h5><span class="badge bg-primary">GET</span> /api/documents/{doc_id}/files/{file_name}</h5>
                        </div>
                        <div class="card-body">
                            <p><strong>功能:</strong> 获取文档中指定文件的内容</p>
                            <p><strong>参数:</strong> doc_id - 文档ID, file_name - 文件名</p>
                            <div class="bg-light p-2 rounded">
                                <code>curl -X GET "http://localhost:8080/api/documents/1/files/README.md"</code>
                            </div>
                        </div>
                    </div>

                    <!-- 获取ZIP状态 -->
                    <div class="card api-card method-get">
                        <div class="card-header">
                            <h5><span class="badge bg-primary">GET</span> /api/documents/zip/status</h5>
                        </div>
                        <div class="card-body">
                            <p><strong>功能:</strong> 获取ZIP文件处理状态</p>
                            <p><strong>响应:</strong> 返回ZIP文件数量和处理状态</p>
                            <div class="bg-light p-2 rounded">
                                <code>curl -X GET "http://localhost:8080/api/documents/zip/status"</code>
                            </div>
                        </div>
                    </div>

                    <!-- 上传文档 -->
                    <div class="card api-card method-post">
                        <div class="card-header">
                            <h5><span class="badge bg-success">POST</span> /api/documents/upload</h5>
                        </div>
                        <div class="card-body">
                            <p><strong>功能:</strong> 上传ZIP文件</p>
                            <p><strong>参数:</strong> file - ZIP文件</p>
                            <div class="bg-light p-2 rounded">
                                <code>curl -X POST -F "file=@document.zip" "http://localhost:8080/api/documents/upload"</code>
                            </div>
                        </div>
                    </div>

                    <!-- 测试API -->
                    <div class="card api-card method-get">
                        <div class="card-header">
                            <h5><span class="badge bg-primary">GET</span> /api/documents/test</h5>
                        </div>
                        <div class="card-body">
                            <p><strong>功能:</strong> 测试文档管理API是否正常运行</p>
                            <div class="bg-light p-2 rounded">
                                <code>curl -X GET "http://localhost:8080/api/documents/test"</code>
                            </div>
                        </div>
                    </div>

                    <!-- 系统信息 -->
                    <div class="card api-card method-get">
                        <div class="card-header">
                            <h5><span class="badge bg-info">GET</span> /</h5>
                        </div>
                        <div class="card-body">
                            <p><strong>功能:</strong> 获取系统信息</p>
                            <div class="bg-light p-2 rounded">
                                <code>curl -X GET "http://localhost:8080/"</code>
                            </div>
                        </div>
                    </div>

                    <!-- 健康检查 -->
                    <div class="card api-card method-get">
                        <div class="card-header">
                            <h5><span class="badge bg-info">GET</span> /health</h5>
                        </div>
                        <div class="card-body">
                            <p><strong>功能:</strong> 健康检查</p>
                            <div class="bg-light p-2 rounded">
                                <code>curl -X GET "http://localhost:8080/health"</code>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="text-center mt-5">
                <p class="text-muted">
                    📁 文档存储路径: <code>zip/</code> (上传) → <code>unzip/</code> (解压)<br>
                    🔗 OpenAPI规范: <a href="/openapi.json">http://localhost:8080/openapi.json</a>
                </p>
            </div>
        </div>
    </body>
    </html>
    """
    return HTMLResponse(content=html_content)

@app.get("/redoc", response_class=HTMLResponse)
async def redoc_html():
    """自定义ReDoc页面 - 无外部依赖版本"""
    html_content = """
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>文档管理系统 API - ReDoc</title>
        <style>
            * { box-sizing: border-box; }
            body { 
                margin: 0; 
                font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;
                font-size: 1rem; 
                line-height: 1.5; 
                color: #212529; 
                background-color: #f8f9fa; 
            }
            .container { 
                max-width: 1140px; 
                margin: 0 auto; 
                padding: 2rem; 
                text-align: center;
            }
            h1 { color: #007bff; margin-bottom: 1rem; }
            .alert { 
                padding: 1rem; 
                margin: 1rem 0; 
                border: 1px solid #bee5eb; 
                border-radius: 0.25rem; 
                background-color: #d1ecf1; 
                color: #0c5460;
            }
            a { color: #007bff; text-decoration: none; }
            a:hover { text-decoration: underline; }
            .btn {
                display: inline-block;
                padding: 0.5rem 1rem;
                margin: 0.5rem;
                background-color: #007bff;
                color: white;
                border: none;
                border-radius: 0.25rem;
                text-decoration: none;
            }
            .btn:hover { background-color: #0056b3; color: white; }
        </style>
    </head>
    <body>
        <div class="container">
            <h1>📚 API 文档</h1>
            <div class="alert">
                <p><strong>文档管理系统 API 文档</strong></p>
                <p>由于服务器环境限制，ReDoc 需要外部资源支持。</p>
                <p>请使用我们的自定义 API 文档页面获得更好的体验。</p>
            </div>
            <a href="/docs" class="btn">📖 查看 API 文档</a>
            <a href="/openapi.json" class="btn">📄 OpenAPI 规范</a>
            <a href="/api/test" class="btn">🧪 文档管理界面</a>
        </div>
    </body>
    </html>
    """
    return HTMLResponse(content=html_content)

@app.get("/")
def read_root():
    """API根路径，返回系统信息"""
    return {
        "message": "WebAPI - 公交站查询系统",
        "version": "1.0.0",
        "status": "running",
        "docs": "/docs",
        "redoc": "/redoc",
        "modules": [
            "文档管理",
            "ZIP文件管理"
        ]
    }

@app.get("/health")
def health_check():
    """健康检查端点 - Docker部署专用"""
    return {"status": "healthy", "service": "document-management"}

# 包含核心路由 - 临时只启用文档管理功能
# app.include_router(bus_station.router, tags=["公交站查询"])
# app.include_router(user.router, prefix="/api", tags=["用户管理"])
app.include_router(documents.router, prefix="/api", tags=["文档管理"])
# app.include_router(calendar.router, tags=["老黄历日历"])
# app.include_router(weather.router, tags=["天气查询"])
app.include_router(zip_manager.router, prefix="/api", tags=["ZIP管理"])
# app.include_router(wechat_management.router, tags=["微信管理"])